package com.dragons.dragonsvf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragons.dragonsvf.dao.UserInfoMapper;
import com.dragons.dragonsvf.entities.ResponseDTO;
import com.dragons.dragonsvf.entities.UserDTO;
import com.dragons.dragonsvf.entities.UserInfo;
import com.dragons.dragonsvf.entities.UserInfoDTO;
import com.dragons.dragonsvf.utils.netUtils;
import com.dragons.dragonsvf.utils.secret.AesEncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class LoginCtrl {

    private static final Logger logger = LoggerFactory.getLogger(LoginCtrl.class);

    @Autowired
    private UserInfoMapper userInfoMapper;


    @RequestMapping("/test")
    public String test() {
        return "测试测试";
    }


    /** 模拟用户 登录 */
    @RequestMapping("/login")
    public ResponseDTO login(@RequestBody UserDTO user) {

        //String token = JwtUtil.createToken(dbUser);
        String encrypt = "";
        if(!"".equals(user.getuPwdword())) {
            try {
                encrypt = AesEncryptUtil.encrypt(user.getuPwdword());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        QueryWrapper<UserInfo> u = new QueryWrapper<>();
        u.eq("username", user.getuName())
            .select("*");
        List<UserInfo> checkPwd = userInfoMapper.selectList(u);

        QueryWrapper<UserInfo> u1 = new QueryWrapper<>();
        u1.eq("username", user.getuName())
            .eq("encrypt_pwd", encrypt)
            .select("*");
        List<UserInfo> userInfos = userInfoMapper.selectList(u1);
        ResponseDTO res = new ResponseDTO();
        if (checkPwd.size() > 0) { // 验证用户是否存在
            if(userInfos.size() > 0) { // 验证密码
                res.setCode(200);
                res.setMsg("登录成功！");
                UserInfo userInfo = userInfos.get(0);
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                // 复制属性（注意参数顺序：源对象在前，目标对象在后）
                BeanUtils.copyProperties(userInfo, userInfoDTO);
                String avatarBase64 = netUtils.convertToBase64(userInfo.getAvatar_url());
                userInfoDTO.setAvatarBase64(avatarBase64);
                res.setData(userInfoDTO);
            } else {
                res.setCode(200);
                res.setMsg("密码错误！");
            }
        } else {
            res.setCode(200);
            res.setMsg("用户不存在！");
        }
        return res;
    }


}
